from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import SportRecords, User
import uuid
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.h_result import HResult
from datetime import datetime
from utils.utils import query_page_list
from utils.utils import to_beijing_time
# import logging
# logging.basicConfig()
# logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

bp = Blueprint('sport_records', __name__, url_prefix='/sport-records/')

class AddSportRecord(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        type_id = data.get('type_id')
        path = data.get('path')
        current_user = get_jwt_identity()
        
        if not type_id or not path:
            return HResult().get_result('error', '参数错误!')
            
        user = User.query.filter_by(name=current_user).first()
        
        record = SportRecords(
            id=str(uuid.uuid4()),
            user_id=user.id,
            type_id=type_id,
            path=path,
            create_time=to_beijing_time(datetime.utcnow())
        )
        
        # 可选字段
        optional_fields = ['name', 'quote_record_id', 'big_img']
        for field in optional_fields:
            if field in data:
                setattr(record, field, data[field])
            
        db.session.add(record)
        db.session.commit()
        return HResult().get_result('success', '记录添加成功!', record.to_dict())

class DeleteSportRecord(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        record_ids = data['ids']
        current_user = get_jwt_identity()
        user = User.query.filter_by(name=current_user).first()
        
        for record_id in record_ids:
            record = SportRecords.query.filter_by(id=record_id).first()
            if record and record.user_id == user.id:
                db.session.delete(record)
                
        db.session.commit()
        return HResult().get_result('success', '删除成功!')

class UpdateSportRecord(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        record_id = data['id']
        # record_data = data['record']
        current_user = get_jwt_identity()
        
        record = SportRecords.query.filter_by(id=record_id).first()
        if not record:
            return HResult().get_result('error', '记录不存在!')
            
        user = User.query.filter_by(name=current_user).first()
        if record.user_id != user.id:
            return HResult().get_result('error', '无权修改此记录!')
            
        for key, value in data.items():
            if key not in ['id', 'user_id', 'create_time']:
                setattr(record, key, value)
        
        db.session.commit()
        return HResult().get_result('success', '修改成功!')

class SportRecordInfo(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        record_id = request.args.get('id')
        record = SportRecords.query.filter_by(id=record_id).first()
        
        if not record:
            return HResult().get_result('error', '记录不存在!')
            
        data = record.to_dict()
        # 添加关联数据
        # 用户信息
        data['user'] = record.user.to_dict()
        # 引用路线
        if record.quote_record:
            data['quote_record'] = record.quote_record.to_dict()
        # 运动类型
        data['type'] = record.type.to_dict()
            
        return HResult().get_result('success', data=data)

class QueryUserSportRecords(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        # user_id = request.args.get('user_id')
        # if not user_id:
        #     return HResult().get_result('error', '参数错误!')
        data = request.get_json()

        # 分页查询
        # records = SportRecords.query.filter(SportRecords.user_id == data['user_id']).offset(0).limit(10).all()
        result = query_page_list(
            model_class=SportRecords,
            page_size=data['pageSize'],
            page_no=data['pageNo'],
            params=data['params'],
            order_by=SportRecords.create_time.desc()
        )

        return HResult().get_result('success', data=result)

api = Api(bp)
api.add_resource(AddSportRecord, '/add/', endpoint='add')
api.add_resource(DeleteSportRecord, '/delete/', endpoint='delete')
api.add_resource(UpdateSportRecord, '/update/', endpoint='update')
api.add_resource(SportRecordInfo, '/info/', endpoint='info')
api.add_resource(QueryUserSportRecords, '/list/', endpoint='list') 